use actix::{Handler, Context, StreamHandler, ActorContext};
use crate::service::model::chat_handler_model::{Connection, Disconnect, WsRequest, ClientMessage};
use crate::service::server::chat::ChatServer;
use crate::service::model::chat_handler_model;
use actix::dev::MessageResponse;
use crate::service::routes::websocket::ws_request;
use crate::service::server::chat_session::ChatSession;
use actix_web_actors::ws::Message;

//连接
impl Handler<Connection> for ChatServer{
    type Result = ();

    fn handle(&mut self, msg: Connection,  _ctx: &mut Context<Self>) -> Self::Result {
        if self.session.contains_key(&msg.id) {
            self.send_disconnect(msg.id,);
        }
        self.session.insert(msg.id,msg.addr);
    }
}

//断连
impl Handler<Disconnect> for ChatServer{
    type Result = ();

    fn handle(&mut self, msg: Disconnect, _ctx: &mut Context<Self>) -> Self::Result {
       self.session.remove(&msg.id);
    }
}

impl Handler<WsRequest> for ChatServer{
    type Result = ();

    fn handle(&mut self, msg: WsRequest, _ctx: &mut Context<Self>) -> Self::Result {
        futures::executor::block_on(async{
            let result=ws_request(&self.pool,&mut self.redis,msg.id,msg.text).await.unwrap();

            for response in result{
                self.send_message(response.id,&response.text)
            }

        });
    }
}

impl Handler<ClientMessage> for ChatServer {
    type Result = ();

    fn handle(&mut self, msg: ClientMessage, _ctx: &mut Self::Context) -> Self::Result {
       self.send_message(msg.id,&msg.msg);
    }
}

impl  Handler<chat_handler_model::Message> for ChatSession{
    type Result = ();

    fn handle(&mut self, msg: chat_handler_model::Message,ctx: &mut Self::Context) -> Self::Result {
        if msg.1{
            ctx.text(msg.0);
        }else{
            ctx.stop();
        }
    }
}


